#include "settingsmanager.h"
#include <QApplication>
#include <QScreen>
#include <QDir>
#include <QStandardPaths>
#include <QDebug>

SettingsManager::SettingsManager(QObject *parent) : QObject(parent),
    m_settings(new QSettings(QSettings::IniFormat, QSettings::UserScope,
                             QCoreApplication::organizationName(),
                             QCoreApplication::applicationName())),
    m_theme(LightTheme),
    m_previewMode(PreviewHorizontal),
    m_font(QApplication::font()),
    m_windowSize(1024, 768),
    m_language(Chinese),
    m_autoSaveInterval(5),
    m_pluginsDirectory(QStandardPaths::writableLocation(QStandardPaths::AppDataLocation) + QDir::separator() + "plugins")
{
    // 初始化默认字体
    m_font.setFamily("Consolas, 'Courier New', monospace");
    m_font.setPointSize(12);

    // 确保插件目录存在
    QDir pluginDir(m_pluginsDirectory);
    if (!pluginDir.exists()) {
        pluginDir.mkpath(".");
    }
}

SettingsManager::~SettingsManager()
{
    delete m_settings;
}

void SettingsManager::initDefaults()
{
    // 设置默认窗口位置为屏幕中心
    QScreen *screen = QApplication::primaryScreen();
    if (screen) {
        QRect screenGeometry = screen->availableGeometry();
        m_windowPosition = QPoint(
            (screenGeometry.width() - m_windowSize.width()) / 2,
            (screenGeometry.height() - m_windowSize.height()) / 2
        );
    }

    // 默认启用的插件
    m_enabledPlugins = {"exportpdf", "imageupload"};
}

void SettingsManager::load()
{
    // 加载前先设置默认值
    initDefaults();

    // 开始从配置文件加载设置
    m_settings->beginGroup("Appearance");
    m_theme = static_cast<Theme>(m_settings->value("Theme", m_theme).toInt());
    m_font = m_settings->value("Font", m_font).value<QFont>();
    m_settings->endGroup();

    m_settings->beginGroup("Editor");
    m_previewMode = static_cast<PreviewMode>(m_settings->value("PreviewMode", m_previewMode).toInt());
    m_autoSaveInterval = m_settings->value("AutoSaveInterval", m_autoSaveInterval).toInt();
    m_settings->endGroup();

    m_settings->beginGroup("Window");
    m_windowSize = m_settings->value("Size", m_windowSize).toSize();
    m_windowPosition = m_settings->value("Position", m_windowPosition).toPoint();
    m_settings->endGroup();

    m_settings->beginGroup("Locale");
    m_language = static_cast<Language>(m_settings->value("Language", m_language).toInt());
    m_settings->endGroup();

    m_settings->beginGroup("RecentFiles");
    m_recentFiles = m_settings->value("List", m_recentFiles).toStringList();
    m_settings->endGroup();

    m_settings->beginGroup("Plugins");
    m_pluginsDirectory = m_settings->value("Directory", m_pluginsDirectory).toString();
    m_enabledPlugins = m_settings->value("EnabledPlugins", m_enabledPlugins).toStringList();
    m_settings->endGroup();

    // 验证窗口大小是否有效
    if (m_windowSize.width() < 640 || m_windowSize.height() < 480) {
        m_windowSize = QSize(1024, 768);
    }

    // 验证自动保存间隔
    if (m_autoSaveInterval < 1 || m_autoSaveInterval > 60) {
        m_autoSaveInterval = 5;
    }
}

void SettingsManager::save()
{
    m_settings->beginGroup("Appearance");
    m_settings->setValue("Theme", m_theme);
    m_settings->setValue("Font", m_font);
    m_settings->endGroup();

    m_settings->beginGroup("Editor");
    m_settings->setValue("PreviewMode", m_previewMode);
    m_settings->setValue("AutoSaveInterval", m_autoSaveInterval);
    m_settings->endGroup();

    m_settings->beginGroup("Window");
    m_settings->setValue("Size", m_windowSize);
    m_settings->setValue("Position", m_windowPosition);
    m_settings->endGroup();

    m_settings->beginGroup("Locale");
    m_settings->setValue("Language", m_language);
    m_settings->endGroup();

    m_settings->beginGroup("RecentFiles");
    m_settings->setValue("List", m_recentFiles);
    m_settings->endGroup();

    m_settings->beginGroup("Plugins");
    m_settings->setValue("Directory", m_pluginsDirectory);
    m_settings->setValue("EnabledPlugins", m_enabledPlugins);
    m_settings->endGroup();

    // 确保立即写入磁盘
    m_settings->sync();
}

void SettingsManager::setTheme(Theme theme)
{
    if (m_theme != theme) {
        m_theme = theme;
        emit themeChanged(theme);
    }
}

void SettingsManager::setPreviewMode(PreviewMode mode)
{
    if (m_previewMode != mode) {
        m_previewMode = mode;
        emit previewModeChanged(mode);
    }
}

void SettingsManager::setFont(const QFont &font)
{
    if (m_font != font) {
        m_font = font;
        emit fontChanged(font);
    }
}

void SettingsManager::setWindowSize(const QSize &size)
{
    if (size.isValid() && m_windowSize != size) {
        m_windowSize = size;
    }
}

void SettingsManager::setWindowPosition(const QPoint &pos)
{
    if (pos.isValid() && m_windowPosition != pos) {
        m_windowPosition = pos;
    }
}

void SettingsManager::setLanguage(Language lang)
{
    if (m_language != lang) {
        m_language = lang;
        emit languageChanged(lang);
    }
}

void SettingsManager::setAutoSaveInterval(int interval)
{
    if (interval >= 1 && interval <= 60 && m_autoSaveInterval != interval) {
        m_autoSaveInterval = interval;
    }
}

void SettingsManager::setRecentFiles(const QStringList &files)
{
    if (m_recentFiles != files) {
        m_recentFiles = files;
        emit recentFilesChanged(files);
    }
}

void SettingsManager::addRecentFile(const QString &path, int maxCount)
{
    QStringList newRecentFiles = m_recentFiles;

    // 如果文件已存在，先移除
    newRecentFiles.removeAll(path);
    // 添加到列表开头
    newRecentFiles.prepend(path);
    // 限制数量
    while (newRecentFiles.size() > maxCount) {
        newRecentFiles.removeLast();
    }

    setRecentFiles(newRecentFiles);
}

void SettingsManager::clearRecentFiles()
{
    setRecentFiles(QStringList());
}

void SettingsManager::setPluginsDirectory(const QString &path)
{
    if (m_pluginsDirectory != path) {
        m_pluginsDirectory = path;
        // 确保目录存在
        QDir dir(path);
        if (!dir.exists()) {
            dir.mkpath(".");
        }
        emit pluginsChanged();
    }
}

void SettingsManager::setEnabledPlugins(const QStringList &plugins)
{
    if (m_enabledPlugins != plugins) {
        m_enabledPlugins = plugins;
        emit pluginsChanged();
    }
}

bool SettingsManager::isPluginEnabled(const QString &pluginName) const
{
    return m_enabledPlugins.contains(pluginName);
}

void SettingsManager::setPluginEnabled(const QString &pluginName, bool enabled)
{
    QStringList newEnabledPlugins = m_enabledPlugins;

    if (enabled && !newEnabledPlugins.contains(pluginName)) {
        newEnabledPlugins.append(pluginName);
        setEnabledPlugins(newEnabledPlugins);
    } else if (!enabled && newEnabledPlugins.contains(pluginName)) {
        newEnabledPlugins.removeAll(pluginName);
        setEnabledPlugins(newEnabledPlugins);
    }
}